﻿using System;
using System.Configuration;
using System.Windows.Forms;
using ConfigurationManagement.Data;

namespace ConfigurationManagement.Administration.UI
{
    public partial class ConnectionStringForm : Form
    {
        public ConnectionStringForm()
        {
            InitializeComponent();
        }

        private void ConnectionStringFormLoad(object sender, EventArgs e)
        {
            ConnectionStringTextBox.Text =
                ConfigurationManager.ConnectionStrings[Constants.ConnectionStringKey].ConnectionString;
        }

        private void ChangeConnectionStringButtonClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ConnectionStringTextBox.Text))
            {
                MessageBox.Show(@"Invalid connection string");
                return;
            }

            var database = new ConfigurationManagementDataContext(ConnectionStringTextBox.Text);
            var exists = database.DatabaseExists();

            if (exists)
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.ConnectionStrings.ConnectionStrings[Constants.ConnectionStringKey].ConnectionString =
                    ConnectionStringTextBox.Text;
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("connectionStrings");
                var parent = MdiParent as Host;
                if (parent != null) parent.UpdateToolString();

                MessageBox.Show(
                    ConfigurationManager.ConnectionStrings[Constants.ConnectionStringKey].ConnectionString ==
                    ConnectionStringTextBox.Text
                        ? @"The connection string has been changed"
                        : @"The connection string has not been changed");
            }
            else
                MessageBox.Show(@"The database could not be opened, please check your connection string");
        }
    }
}